package sgt.onlinetest.hibernatedao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;

public abstract class HibernateGenericDAO<T, TId extends Serializable> {

    private Class<T> persistentClass;
    private Session session;

    public HibernateGenericDAO(Session session) {
        this.session = session;
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    protected Session getSession() {
        return session;
    }

    public Class<T> getPersistentClass() {
        return persistentClass;
    }

    public T getById(TId id) {
        T entity;
        entity = (T) getSession().load(getPersistentClass(), id);

        return entity;
    }

    public List<T> getAll() {
        return getByCriteria();
    }

    public T save(T entity, boolean delayFlushing) {
        getSession().saveOrUpdate(entity);
        if (!delayFlushing) {
            getSession().flush();
        }
        return entity;
    }

    public T[] save(T[] entities, boolean delayFlushing) {
        for (T entity : entities) {
            getSession().saveOrUpdate(entity);
        }
        if (!delayFlushing) {
            getSession().flush();
        }
        return entities;
    }

    public T save(T entity) {
        return save(entity, false);
    }

    public T[] save(T[] entities) {
        return save(entities, false);
    }

    /**
     * Delete object and execute delete command right away
     * @param entity
     */
    public void delete(T entity) {
        delete(entity, false);
    }

    /**
     * Delete object
     * @param entity
     * @param delayFlushing Indicate whether the SQL delete command should be executed right away or not.
     */
    public void delete(T entity, boolean delayFlushing) {
        getSession().delete(entity);
        if (!delayFlushing) {
            flush();
        }
    }

    public void flush() {
        getSession().flush();
    }

    public void clear() {
        getSession().clear();
    }

    /**
     * Use this inside subclasses as a convenience method.
     */
    protected List<T> getByCriteria(Criterion... criterion) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        for (Criterion c : criterion) {
            crit.add(c);
        }
        return crit.list();
    }
}
